﻿using Furion.Authorization;
using Furion.DataEncryption;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System;
using System.Security.Claims;
using System.Threading.Tasks;

namespace furion.blog.Web.Core;

public class JwtHandler : AppAuthorizeHandler
{

    public override async Task HandleAsync(AuthorizationHandlerContext context)
    {
        Console.WriteLine("进入jwt验证");

        var currentHttpContext = context.GetCurrentHttpContext();
        string token = currentHttpContext.Request.Headers["token"].ToString();
        // 检查并自动刷新 token, (第三个参数,新token有效期设置为1分钟,便于测试)
        if (!string.IsNullOrEmpty(token))
        {
            //校验token
            var (isVaild, tokenInfo, validationResult) = JWTEncryption.Validate(token);
            if (!isVaild)
            {
                //校验不通过
                context.Fail();
            }
            else
            {
                string role = tokenInfo.GetClaim("role").Value;
                string id = tokenInfo.GetClaim("id").Value;

                Console.WriteLine("当前请求角色============>" + role);
                //放行请求
                if (role == "User")
                {
                    //后台账号
                    currentHttpContext.Request.Headers["UserId"] = id;
                    currentHttpContext.Request.Headers["UserRole"] = role;
                } else if (role == "Member") {
                    //app会员
                    currentHttpContext.Request.Headers["MemberId"] = id;
                    currentHttpContext.Request.Headers["UserRole"] = role;
                }
                await AuthorizeHandleAsync(context);
            }
        }
        else
        {
            context.Fail();// 授权失败
        }
    }

    public override Task<bool> PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
    {
        // 检查权限，如果方法时异步的就不用 Task.FromResult 包裹，直接使用 async/await 即可
        // 这里写您的授权判断逻辑，授权通过返回 true，否则返回 false

        return Task.FromResult(true);
    }
}
